package gulimall.ware.service.impl;

import gulimall.constant.WareConstant;
import gulimall.utils.R;
import gulimall.ware.entity.PurchaseDetailEntity;
import gulimall.ware.entity.WareSkuEntity;
import gulimall.ware.feign.ProductFeignService;
import gulimall.ware.service.PurchaseDetailService;
import gulimall.ware.service.WareSkuService;
import gulimall.ware.vo.MergeVo;
import gulimall.ware.vo.PurchaseDoneVo;
import gulimall.ware.vo.PurchaseItemDoneVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import gulimall.utils.PageUtils;
import gulimall.utils.Query;

import gulimall.ware.dao.PurchaseDao;
import gulimall.ware.entity.PurchaseEntity;
import gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Resource
    private PurchaseDao purchaseDao;
    @Resource
    private PurchaseDetailService purchaseDetailService;
    @Resource
    private WareSkuService wareSkuService;
    @Resource
    private ProductFeignService productFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> queryWrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        String status = (String) params.get("status");
        if (StringUtils.isNotBlank(status)){
            queryWrapper.lambda().eq(PurchaseEntity::getStatus,status);
        }
        if (StringUtils.isNotBlank(key)){
            queryWrapper.lambda().and(wrapper ->{
                wrapper.eq(PurchaseEntity::getId,key)
                        .or().eq(PurchaseEntity::getAssigneeId,key)
                        .or().like(PurchaseEntity::getAssigneeName,key);
            });
        }

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    /**
     * 查询未领取的采购单，即采购单状态为新建(status=0)
     * 已分配的采购单(status=1)也可以被重新分配
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryUnReceivePage(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(PurchaseEntity::getStatus, 0)
                .or().eq(PurchaseEntity::getStatus, 1);

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    /**
     * 合并采购项(采购需求)成采购单
     *
     * @param mergeVo
     */
    @Override
    @Transactional
    public void saveMerge(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();//采购单Id
        List<Long> items = mergeVo.getItems();//采购项(采购需求)id集合
        if (purchaseId == null) {//如果采购单id为null，就需要新建一个采购单
            PurchaseEntity purchase = new PurchaseEntity();
            purchase.setPriority(1);//设置采购单默认优先级
            purchase.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());//设置采购单状态为新建状态
            purchaseDao.insert(purchase);
            purchaseId = purchase.getId();
        }
        //将采购项合并到采购单中
        List<PurchaseDetailEntity> purchaseDetails = purchaseDetailService.listByIds(items);
        Long finalPurchaseId = purchaseId;
        purchaseDetails = purchaseDetails.stream().peek(purchaseDetail -> {
            //1.修改采购需求表中的数据
            purchaseDetail.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());//修改状态为已分配
            purchaseDetail.setPurchaseId(finalPurchaseId);//设置采购单id
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(purchaseDetails);

        //TODO 2.修改采购单表中的总金额
    }

    /**
     * 领取采购单(改变采购单的状态为已领取，改变采购项<采购需求>的状态为正在采购)
     *
     * @param ids 采购单id集合
     */
    @Override
    @Transactional
    public void updateStatusByPurchaseIds(List<Long> ids) {
        //1.改变采购单的状态
        List<PurchaseEntity> purchaseEntities = this.listByIds(ids);
        purchaseEntities = purchaseEntities.stream().peek(purchaseEntity -> {
            //如果当前采购单是新建或者是已分配状态才可以被领取
            if (purchaseEntity.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode()
                    || purchaseEntity.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
                //将采购单的状态改变为已领取
                purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.RECEIVED.getCode());
            }
        }).collect(Collectors.toList());
        this.updateBatchById(purchaseEntities);

        //2.改变采购单对应的采购项的状态
        ids.forEach(purchaseId -> {
            //找出purchaseId对应的所有PurchaseDetailEntity
            List<PurchaseDetailEntity> list = purchaseDetailService.list(
                    new QueryWrapper<PurchaseDetailEntity>()
                            .lambda().eq(PurchaseDetailEntity::getPurchaseId, purchaseId)
            );
            list = list.stream().peek(purchaseDetailEntity -> {
                //如果当前采购项是新建或者是已分配状态才可以被领取
                if (purchaseDetailEntity.getStatus() == WareConstant.PurchaseDetailStatusEnum.CREATED.getCode()
                        || purchaseDetailEntity.getStatus() == WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode()) {
                    //将采购项的状态改为正在采购
                    purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                }
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(list);
        });
    }

    /**
     * 完成采购
     *
     * @param purchaseDoneVo
     */
    @Override
    @Transactional
    public void donePurchase(PurchaseDoneVo purchaseDoneVo) {
        //1.改变采购项的状态
        List<PurchaseItemDoneVo> items = purchaseDoneVo.getItems();
        AtomicBoolean flag = new AtomicBoolean(true);//如果有一个采购项的状态不是已完成，则flag就设置为false
        List<PurchaseDetailEntity> detailEntityList = items.stream().map(item -> {
            PurchaseDetailEntity purchaseDetailEntity = purchaseDetailService.getById(item.getItemId());
            purchaseDetailEntity.setStatus(item.getStatus());
            if (item.getStatus() != WareConstant.PurchaseDetailStatusEnum.FINISH.getCode()) {
                flag.set(false);
            } else {
                //3.将成功采购的入库(更改商品库存)
                WareSkuEntity wareSkuEntity = new WareSkuEntity();

                Long skuId = purchaseDetailEntity.getSkuId();
                Long wareId = purchaseDetailEntity.getWareId();
                Integer skuNum = purchaseDetailEntity.getSkuNum();

                //TODO 如果远程调用失败进行熔断降级
                R skuInfoR = productFeignService.skuNameById(skuId);
                if (skuInfoR.getCode() == 0) {
                    String skuName = (String) skuInfoR.get("skuName");
                    wareSkuEntity.setSkuName(skuName);
                }

                wareSkuEntity.setSkuId(skuId);
                wareSkuEntity.setWareId(wareId);
                wareSkuEntity.setStock(skuNum);
                wareSkuService.addStock(wareSkuEntity);
            }
            return purchaseDetailEntity;
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(detailEntityList);

        //2.改变采购单的状态(根据采购项的状态决定，所有采购项都完成后，采购单状态才是已完成，否则就是有异常)
        PurchaseEntity purchaseEntity = purchaseDao.selectById(purchaseDoneVo.getId());
        if (flag.get()) {
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.FINISH.getCode());
        } else {
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        }
        purchaseDao.updateById(purchaseEntity);

    }

}